package com.sd.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.alex.books.BaseBook;
import com.alex.books.BookMark;
import com.alex.books.BookPageFactory;
import com.alex.books.BookStore;
import com.alex.books.Chapter;
import com.alex.books.ReaderingInfo;
import com.alex.database.BookDao;
import com.alex.database.BookDatabaseHelper.Book_TB;
import com.alex.exception.UnsupportedFormatException;
import com.sd.reader.ReaderFlipper;
import com.sd.reader.ReaderSet;

/**
 * 
 * 阅读界面
 * 
 * @author Alex.Lu
 *
 */
public class ReaderActivity extends Activity implements OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener{

	private final String TAG = "ReaderActivity";
	public static String READINGINFO = "readeringinfo";
	public static String BOOK_ID = "book_id";
	private BaseBook mBaseBook;
	
	/**
	 * 阅读器
	 */
	private ReaderFlipper mReader;
	
	/**
	 * 顶部操作区
	 */
	private RelativeLayout mTitleRL;
	/**
	 * 标题栏
	 */
	private TextView mTitleTV;
	/**
	 * 返回
	 */
	private Button mReturnBT;
	/**
	 * 目录
	 */
	private Button mContentsBT;
	/**
	 * 书签按钮
	 */
	private Button mBookMark;
	
	
	/**
	 * 底部设置栏
	 */
	private LinearLayout mBottomLL;
	/**
	 * 阅读设置栏
	 */
	private LinearLayout mReadSetLL;
	/**
	 * 夜间模式和白天模式的
	 */
	private CheckBox mReadModelBT;
	/**
	 * 阅读设置
	 */
	private Button mReadSetBT;
	/**
	 * 在线书城
	 */
	private Button mOnlineCityBT;
	/**
	 * 转屏
	 */
	private Button mRotateScreenBT;
	/**
	 * 更多操作
	 */
	private Button mMoreOpterationBT;
	
	
	/**
	 * 阅读设置
	 */
	/**
	 * 加大字体
	 */
	private Button mFontSizeDecreaseBT;
	/**
	 * 减小行间距
	 */
	private Button mFontSizeIncreaseBT;
	/**
	 * 加大行间距
	 */
	private Button mLineSpaceDecreaseBT;
	/**
	 * 减小字体
	 */
	private Button mLineSpaceIncreaseBT;
	/**
	 * 调节亮度
	 */
	private SeekBar mSeekBar;
	/**
	 * 背景切换
	 */
	private LinearLayout mThemeBgLL;
	/**
	 * 翻页模式
	 */
	private LinearLayout mFilpModeLL;
	
	private Handler handler;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
        setContentView(R.layout.reader_activity);
        
        initFindView();
        
        initBookPageFactory();
        
	}
	
	/**
	 * 初始化
	 */
	private void initFindView(){
		mReader = (ReaderFlipper)findViewById(R.id.reader);
	    mReader.setOnSingleTapUpListener(this);
		initTitleLL();
		initBottomLL();
		initReadSetLL();
		mReader.setmTitleTV(mTitleTV);
	}
	
	private void initBookPageFactory(){
		mBaseBook = new BaseBook();
		Intent intent = this.getIntent();
		mBaseBook = BookStore.getInstance().getABook(this, intent.getIntExtra(BOOK_ID, 0));
        
		/*BookPageFactory1.getInstance().setChapter(mBook.markChapter);
		BookPageFactory1.getInstance().setPostion(mBook.mark);
			
		BookPageFactory1.getInstance().openBook(mBook.path,mCursor);
		if(mBook.isFirstRead == 1){
			 handler = new Handler(){
		        	@Override
		        	public void handleMessage(Message msg) {
		        		// TODO Auto-generated method stub
		        		GenerationContents genera = new GenerationContents(ReaderActivity.this);
		                genera.openBook(mBook.path,mBook.id);
		                mBook.isFirstRead = 0;
		                BookDao.getInstance().updateBook(ReaderActivity.this, mBook);
		        		super.handleMessage(msg);
		        	}
		        };
		        handler.sendEmptyMessage(1);
		}*/
        
		try {
			BookPageFactory.getInstance().openBook(this,mBaseBook);
			//BookPageFactory.getInstance().setReaderingInfo(readeringInfo)
			BookPageFactory.getInstance().setReaderFormat(24, 0, 480, 800);
	        
			mReader.setReaderTextSize(24);
			mReader.nextPage();
		} catch (UnsupportedFormatException e) {
			// TODO Auto-generated catch block
			Toast.makeText(this, "不好意思，不支持格式："+e.getMessage(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}
	
	/**
	 * 标题栏操作
	 */
	private void initTitleLL(){
		mTitleTV = (TextView)findViewById(R.id.title);
		mTitleRL = (RelativeLayout)findViewById(R.id.title_operation);
		mReturnBT = (Button)findViewById(R.id.btn_return);
		mReturnBT.setOnClickListener(this);
		mContentsBT = (Button)findViewById(R.id.btn_contents);
		mContentsBT.setOnClickListener(this);
		mBookMark = (Button)findViewById(R.id.btn_bookmark);
		mBookMark.setOnClickListener(this);
		
/*		String title = mBook.markChapter.chapterName;
		if(title != null && title.length() > 6){
			title = title.substring(0,6);
		}
		mTitleTV.setText(title);*/
	}
	
	/**
	 * 初始化底部操作栏
	 */
	private void initBottomLL(){
		mBottomLL = (LinearLayout)findViewById(R.id.bottom_operation);
		mReadModelBT = (CheckBox)findViewById(R.id.btn_read_model);
	    mReadModelBT.setChecked(true);
	    mReadModelBT.setOnCheckedChangeListener(this);
	    mReadSetBT= (Button)findViewById(R.id.btn_read_set);
	    mReadSetBT.setOnClickListener(this);
	    mOnlineCityBT = (Button)findViewById(R.id.btn_online_city);
	    mOnlineCityBT.setOnClickListener(this);
	    mRotateScreenBT = (Button)findViewById(R.id.btn_rotate_screen);
	    mRotateScreenBT.setOnClickListener(this);
	    mMoreOpterationBT = (Button)findViewById(R.id.btn_more_opteration);
	    mMoreOpterationBT.setOnClickListener(this);
	}
	/**
	 * 初始化阅读操作
	 */
	private void initReadSetLL(){
		mReadSetLL = (LinearLayout)findViewById(R.id.read_set_layout);
		mReadSetLL.setVisibility(View.GONE);
		
		mSeekBar = (SeekBar)findViewById(R.id.brightness_seek_bar);
		mSeekBar.setOnSeekBarChangeListener(this); 
		int a =getScreenBrightness(this);  
		mSeekBar.setProgress(a);
		
		mFontSizeDecreaseBT = (Button)findViewById(R.id.font_size_decrease);
		mFontSizeDecreaseBT.setOnClickListener(this);
		
		mFontSizeIncreaseBT = (Button)findViewById(R.id.font_size_increase);
		mFontSizeIncreaseBT.setOnClickListener(this);
		
		mLineSpaceDecreaseBT = (Button)findViewById(R.id.line_space_decrease);
		mLineSpaceDecreaseBT.setOnClickListener(this);
		
		mLineSpaceIncreaseBT = (Button)findViewById(R.id.line_space_increase);
		mLineSpaceIncreaseBT.setOnClickListener(this);
		
		mThemeBgLL = (LinearLayout)findViewById(R.id.theme_bg);
		
		mFilpModeLL = (LinearLayout)findViewById(R.id.flip_mode);
		initData();
	}
	
	private void initData(){
		
		ImageView image = new ImageView(this);
		image.setLayoutParams(new LayoutParams(60, 60));
		image.setBackgroundColor(R.color.antiquewhite);
		image.setTag(R.color.antiquewhite);
		image.setOnClickListener(mlistener);
		mThemeBgLL.addView(image);
		
		ImageView image1 = new ImageView(this);
		image1.setLayoutParams(new LayoutParams(60, 60));
		image1.setBackgroundColor(R.color.aqua);
		image1.setTag(R.color.aqua);
		image1.setOnClickListener(mlistener);
		mThemeBgLL.addView(image1);
		
		Button but = new Button(this);
		but.setText("左右切换");
		but.setTextColor(0xff000000);
		but.setBackgroundColor(R.color.white);
		but.setTag(ReaderFlipper.RIGHTLEFT_DIR);
		but.setOnClickListener(mlistener1);
		mFilpModeLL.addView(but);
		
		Button but1 = new Button(this);
		but1.setText("上下切换");
		but1.setTextColor(0xff000000);
		but1.setBackgroundColor(R.color.white);
		but1.setTag(ReaderFlipper.UPDOWN_DIR);
		but1.setOnClickListener(mlistener1);
		mFilpModeLL.addView(but1);
	}
	
	OnClickListener mlistener = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Integer color = (Integer)v.getTag();
			mReader.setBackgroundColor(color);
		}
	};
	
	OnClickListener mlistener1 = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Integer dir = (Integer)v.getTag();
			mReader.setReaderDir(dir);
		}
	};
	
	private int isReadVisible = View.VISIBLE;
	private int isReadSetVisible = View.GONE;
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();
		switch (v_id) {
		case R.id.reader:
			if(isReadVisible == View.VISIBLE){
				nuvisibility();
				mReadSetLL.setVisibility(View.GONE);
				isReadVisible = View.GONE;
				isReadSetVisible =View.GONE;
			}else if(isReadVisible == View.GONE){
				visibility();
				isReadVisible = View.VISIBLE;
			}
			break;
		case R.id.btn_return:
			finish();
			break;
		case R.id.btn_contents:
			Intent intent = new Intent(getApplicationContext(), SdFirstProjectActivity.class);
			intent.putExtra(SdFirstProjectActivity.BOOKDATA, mBaseBook);
			startActivityForResult(intent, 0);
			break;
		case R.id.btn_bookmark:
			BookStore.getInstance().addBookMark(this, mBaseBook);
			break;
		case R.id.btn_read_set:
			if(isReadSetVisible == View.GONE){
				mReadSetLL.setVisibility(View.VISIBLE);
				isReadSetVisible =View.VISIBLE;
			}else {
				mReadSetLL.setVisibility(View.GONE);
				isReadSetVisible =View.GONE;
			}
			break;
		case R.id.font_size_decrease:
			ReaderSet.getInstance().decreaseFontSize();
			mReader.setReaderTextSize(ReaderSet.getInstance().getmFontSize());
			mReader.reFreshPage();
			break;
		case R.id.font_size_increase:
			ReaderSet.getInstance().increaseFontSize();
			mReader.setReaderTextSize(ReaderSet.getInstance().getmFontSize());
			mReader.reFreshPage();
			break;
		case R.id.line_space_decrease:
			ReaderSet.getInstance().decreaseLineSpace();
			mReader.setLineSpace(ReaderSet.getInstance().getLineSpace());
			mReader.reFreshPage();
			break;
		case R.id.line_space_increase:
			ReaderSet.getInstance().increaseLineSpace();
			mReader.setLineSpace(ReaderSet.getInstance().getLineSpace());
			mReader.reFreshPage();
			break;
		default:
			break;
		}
	}
	
	/**
	 * 搜索返回的结果
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 0) {

			if (resultCode == RESULT_OK) {
				
				ReaderingInfo readeringInfo = (ReaderingInfo)data.getSerializableExtra(READINGINFO);
				BookPageFactory.getInstance().setReaderingInfo(readeringInfo);
				mReader.reFreshPage();
			}
		}
	}
	
	/**
	 * 
	 */
	private void visibility(){
		mTitleRL.setVisibility(View.VISIBLE);
		mBottomLL.setVisibility(View.VISIBLE);
	}
	
	private void nuvisibility(){
		mTitleRL.setVisibility(View.GONE);
		mBottomLL.setVisibility(View.GONE);
	}

	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if(isChecked){
			mReader.setBackgroundColor(0xffffffff);
			mReader.setViewColor(0xff000000);
			mReadModelBT.setText(R.string.btn_read_model_day);
		}else{
			mReader.setBackgroundColor(0xff000000);
			mReader.setViewColor(0xffffffff);
			mReadModelBT.setText(R.string.btn_read_model_night);
		}
	}

	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		if (progress < 10) {  
        } else {
            setBrightness(ReaderActivity.this, progress);  
        } 
	}

	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}
	
	/** 
	 *  
	 * @param activity 
	 * @return 
	 */  
	public static int getScreenBrightness(Activity activity) {  
	    int nowBrightnessValue = 0;  
	    ContentResolver resolver = activity.getContentResolver();  
	    try {  
	        nowBrightnessValue = android.provider.Settings.System.getInt(  
	                resolver, Settings.System.SCREEN_BRIGHTNESS);  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	    return nowBrightnessValue;  
	}  
	  
	/** 
	 * 
	 * @param activity 
	 * @param brightness 
	 */  
	public static void setBrightness(Activity activity, int brightness) {  
	    // Settings.System.putInt(activity.getContentResolver(),  
	    // Settings.System.SCREEN_BRIGHTNESS_MODE,  
	    // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);  
	    WindowManager.LayoutParams lp = activity.getWindow().getAttributes();  
	    lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);  
	    activity.getWindow().setAttributes(lp);  
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		BookDao.getInstance().updateBook(this, mBaseBook);
		super.onDestroy();
	}  
	
	
}
